package com.baselib.android.utils.img;


import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.widget.ImageView;
import com.baselib.android.R;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import org.apache.commons.lang.StringUtils;

/**
 * 图片缓存类
 *
 * @author linxi
 * 异步加载图片
 */
public class ImageLoader {


    Context context;

    int stub_id;
    static ImageLoader instance;


    public void loadLocalImage(String path, ImageView imageView) {

        if (TextUtils.isEmpty(path)
                || null == imageView || contextBad()) {
            return;
        }

        Glide.with(context)
                .load(path)
                .centerCrop()
                .placeholder(R.drawable.default_image)
                .into(imageView);
    }


    public static ImageLoader getInstance(Context context, int iconDefaultResId) {
        if (instance == null) {
            return new ImageLoader(context, iconDefaultResId);
        }
        return instance;
    }

    public static ImageLoader getInstance(Context context) {
        if (instance == null) {
            return new ImageLoader(context, 0);
        }
        return instance;
    }

    public ImageLoader(Context context) {
        this(context, 0);
    }

    public ImageLoader(Context context, int iconDefaultResId) {
        // 默认图片
        this.context = context;
        stub_id = iconDefaultResId;
        String string;


    }

    public void displayLocalImage(String url, ImageView imageView) {
        if (StringUtils.isBlank(url) || contextBad())
            return;
//        url  ="http://mpic.spriteapp.cn/ugc/2017/10/23/59ed16bfa2219.gif";
        url = StringUtils.trim(url);

        if (url.endsWith("gif")) {
            Glide.with(context).load(url).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
            return;
        }
        Glide.with(context)
                .load(url)
                .asBitmap()
                .placeholder(stub_id)
                .into(new MyBitmapImageViewTarget(imageView, ImageView.ScaleType.CENTER_CROP) {
                    @Override
                    public void startLoad() {

                    }

                    @Override
                    public void finishLoad() {

                    }
                });

    }


    public void displayLocalImage1(String url, ImageView imageView) {
        if (StringUtils.isBlank(url) || contextBad())
            return;
//        url  ="http://mpic.spriteapp.cn/ugc/2017/10/23/59ed16bfa2219.gif";
        url = StringUtils.trim(url);

        if (url.endsWith("gif")) {
            Glide.with(context).load(url).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
            return;
        }
        Glide.with(context)
                .load(url)
                .asBitmap()
                .placeholder(stub_id)
                .into(new MyBitmapImageViewTarget(imageView, ImageView.ScaleType.CENTER_INSIDE) {
                    @Override
                    public void startLoad() {

                    }

                    @Override
                    public void finishLoad() {

                    }
                });

    }

    private boolean contextBad() {
        if (context == null) {
            return true;
        }
        if (context instanceof Activity) {
            return ((Activity) context).isFinishing();
        }
        return false;
    }


    public void displayAvatar(String url, ImageView imageView) {
        if (StringUtils.isBlank(url) || contextBad())
            return;
        //url  ="http://mpic.spriteapp.cn/ugc/2017/10/23/59ed16bfa2219.gif";
        if (url.endsWith("gif")) {
            Glide.with(context).load(url).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
            return;
        }
        url = StringUtils.trim(url);
        Glide.with(context)
                .load(getUrl(url))
                .asBitmap()
                .placeholder(R.drawable.iv_fs_avatar_default)
                .error(R.drawable.iv_fs_avatar_default)
                .into(new MyBitmapImageViewTarget(imageView, ImageView.ScaleType.CENTER_CROP) {
                    @Override
                    public void startLoad() {

                    }

                    @Override
                    public void finishLoad() {

                    }
                });


    }

    public void displayAvatar1(String url, ImageView imageView) {
        if (StringUtils.isBlank(url) || contextBad())
            return;
        //url  ="http://mpic.spriteapp.cn/ugc/2017/10/23/59ed16bfa2219.gif";
        if (url.endsWith("gif")) {
            Glide.with(context).load(url).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
            return;
        }
        url = StringUtils.trim(url);
        Glide.with(context)
                .load(getUrl(url))
                .asBitmap()
                .placeholder(R.drawable.iv_fs_avatar_default)
                .error(R.drawable.iv_fs_avatar_default)
                .into(new MyBitmapImageViewTarget(imageView, ImageView.ScaleType.CENTER_INSIDE) {
                    @Override
                    public void startLoad() {

                    }

                    @Override
                    public void finishLoad() {

                    }
                });


    }

    public void displayImage(String url, ImageView imageView, final ImageLoadCallBack callBack) {
        if (StringUtils.isBlank(url) || contextBad())
            return;
        //url  ="http://mpic.spriteapp.cn/ugc/2017/10/23/59ed16bfa2219.gif";
        if (url.endsWith("gif")) {
            Glide.with(context).load(url).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
            return;
        }

        Glide.with(context)
                .load(getUrl(url))
                .asBitmap()
                .into(new MyBitmapImageViewTarget(imageView, ImageView.ScaleType.CENTER_CROP) {
                    @Override
                    public void startLoad() {
                        callBack.startImag();
                    }

                    @Override
                    public void finishLoad() {
                        callBack.finishImag();
                    }
                });
    }


    public void displayImage(String url, ImageView imageView) {
        if (StringUtils.isBlank(url))
            return;
        //url  ="http://mpic.spriteapp.cn/ugc/2017/10/23/59ed16bfa2219.gif";
        if (url.endsWith("gif")) {
            Glide.with(context).load(url).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
            return;
        }

        Glide.with(context)
                .load(url)
                .centerCrop()
                .into(imageView);

    }

//    public void saveImageToGallery1(Context context, Bitmap bitmap) {
//        try {
//
//            //创建一个保存的Uri
//            Uri saveUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
//            if (TextUtils.isEmpty(saveUri.toString())) {
//                return;
//            }
//            if (Build.VERSION.SDK_INT >= 29) {
//                OutputStream outputStream = context.getContentResolver().openOutputStream(saveUri);
//                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
//            } else {
//                saveImageToGallery(context, bitmap);
//            }
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            Log.e("AA", e.getLocalizedMessage());
//        }
//    }

    public void displayImage21(String url, ImageView imageView) {
        if (StringUtils.isBlank(url))
            return;
        //url  ="http://mpic.spriteapp.cn/ugc/2017/10/23/59ed16bfa2219.gif";
        if (url.endsWith("gif")) {
            Glide.with(context).load(url).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
            return;
        }
        Glide.with(context)
                .load(url).fitCenter()
                .into(imageView);

    }

    public void displayImageTop(String url, ImageView imageView) {
        if (StringUtils.isBlank(url))
            return;
        Glide.with(context)
                .load(url)
                .into(imageView);
    }

    public void displayImage12(String url, ImageView imageView) {
        if (StringUtils.isBlank(url))
            return;
        //url  ="http://mpic.spriteapp.cn/ugc/2017/10/23/59ed16bfa2219.gif";
        if (url.endsWith("gif")) {
            Glide.with(context).load(url).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
            return;
        }
        Glide.with(context)
                .load(url)
                .into(imageView);

    }


    public void displayCicleImage(String url, final ImageView imageView) {
        if (StringUtils.isBlank(url))
            return;
        //url  ="http://mpic.spriteapp.cn/ugc/2017/10/23/59ed16bfa2219.gif";
        if (url.endsWith("gif")) {
            Glide.with(context).load(url).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
            return;
        }
        Glide.with(context)
                .load(url)
                .asBitmap()
                .diskCacheStrategy(DiskCacheStrategy.ALL) //设置缓存
                .into(new BitmapImageViewTarget(imageView) {
                    @Override
                    protected void setResource(Bitmap resource) {
//                        RoundedBitmapDrawable circularBitmapDrawable =
//                                RoundedBitmapDrawableFactory.create(context.getResources(), resource);
//                        circularBitmapDrawable.setCircular(true);
//                        imageView.setImageDrawable(circularBitmapDrawable);
                    }
                });

    }


    public void displayImage5(String url, ImageView imageView) {
        if (StringUtils.isBlank(url))
            return;
        //url  ="http://mpic.spriteapp.cn/ugc/2017/10/23/59ed16bfa2219.gif";
        if (url.endsWith("gif")) {
            Glide.with(context).load(url).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
            return;
        }
        Glide.with(context)
                .load(url)
                .into(imageView);

    }


    private String getUrl(String uri) {
        if (uri.startsWith("http")) {
            return uri;
        }
        return "http://" + uri;
    }


    public void downLoadImag() {

    }


//    public void saveImageToGallery(Context context, Bitmap bmp) {
//        // 首先保存图片
//        File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsoluteFile();//注意小米手机必须这样获得public绝对路径
//        String fileName = "yyFile";
//        File appDir = new File(file, fileName);
//        if (!appDir.exists()) {
//            appDir.mkdirs();
//        }
//        fileName = System.currentTimeMillis() + ".jpg";
//        final File currentFile = new File(appDir, fileName);
//
//        FileOutputStream fos = null;
//        try {
//            fos = new FileOutputStream(currentFile);
//            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
//            fos.flush();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if (fos != null) {
//                    fos.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//
//        // 其次把文件插入到系统图库
//        try {
//            MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                    currentFile.getAbsolutePath(), fileName, null);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//
////        try {
//////            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));
////
////            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,UriUtil.getUriFromPath(BaseApp.getInstance().getApplicationContext(),currentFile.getPath()) ));
////            MediaScannerConnection.scanFile(
////                    BaseApp.getInstance().getApplicationContext(),
////                    new String[]{currentFile.getAbsolutePath()},
////                    new String[]{"image/jpeg"},
////                    new MediaScannerConnection.OnScanCompletedListener() {
////                        @Override
////                        public void onScanCompleted(String path, Uri uri) {
////
////                        }
////                    });
////        }catch (Exception e){
////
////        }
////
////        try {
////            Uri uri = Uri.fromFile(currentFile);
////            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
////            intent.setData(uri);
////            context.sendBroadcast(intent);
////        }catch (Exception e){
////
////        }
//        try {
////            Uri uri = Uri.fromFile(currentFile);
//            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
////            intent.setData(uri);
////            context.sendBroadcast(intent);
//
//            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
//                    UriUtil.getUriFromPath(context, currentFile.getPath())));
//            String prider = BaseApp.getInstance().getPackageName() + ".provider";
//            Uri uri = FileProvider.getUriForFile(BaseApp.getInstance(), prider, currentFile);
//            intent.setData(uri);
//            context.sendBroadcast(intent);
//        } catch (Exception e) {
//
//        }
//        try {
//            currentFile.delete();
//        } catch (Exception e) {
//
//        }
//
//        // 最后通知图库更新
//
//
//    }

    public void displayImageStart(String url, ImageView imageView) {
        if (StringUtils.isBlank(url) || contextBad())
            return;
        //url  ="http://mpic.spriteapp.cn/ugc/2017/10/23/59ed16bfa2219.gif";

        Glide.with(context)
                .load(getUrl(url))
                .asBitmap()
                .placeholder(R.drawable.default_image)
                .into(new MyBitmapImageViewTarget(imageView, ImageView.ScaleType.FIT_START) {
                    @Override
                    public void startLoad() {

                    }

                    @Override
                    public void finishLoad() {

                    }
                });


    }


}


